package com.kdtech.analyse.news;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.utils.HtmlCleaner;

/**
 * 云财经
 * @author Persh
 *
 */
public class YunvsNewsAnalyse implements AnalyseNews {
	
	public static HashMap<String, String> getLinks(String url){
		HashMap<String, String> links = new HashMap<String, String>();
		if(StringUtils.isBlank(url)){
			return links;
		}
		
		UrlMeta meta = CrawlHTML.responseToURL(url);
		if(meta == null || StringUtils.isBlank(meta.getHtml())){
			return links;
		}
		
		String htmltxt = meta.getHtml();
		Matcher matcher = Pattern.compile("onclick=\"show_ins\\(([0-9]+)\\)\"").matcher(htmltxt);
		while(matcher.find()){
			links.put("http://yunvs.com/neican/nc" + matcher.group(1) + ".html", "");
		}
		
		return links;
	}
	
	private static final String[] regex={
		"http://yunvs.com/news/n[0-9]*_[0-9]*_1.html",
		"http://yunvs.com/neican/nc[0-9]*.html"
	};
	
	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}		
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();		
				
		news.setUrl(url);		
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		title =doc.select("h1").text();
		doc.select("div.main_content > div").remove();
		content=HtmlCleaner.getContentHtml(url,doc.select("div.main_content"));
		author=JSoupUtils.matchAuthor(doc, "来源：");
		date=DateUtils.matchDate(doc.select("h2").text());

		if(StringUtils.isBlank(title)){
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);	
		
		return news;
	}
	
	public static void main(String[] args) {
		YunvsNewsAnalyse analyse=new YunvsNewsAnalyse();
		String url="http://yunvs.com/neican/nc136801716.html";
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
